import { View, Text } from '@tarojs/components';
import PageContainer from '@/components/PageContainer';
import { getRechargeRecordList, payRechargePackage } from '@/services/payment';
import FlexScrollView from '@/components/FlexScrollView';
import './index.less';
import { useState, useEffect } from 'react';
import { DynamicColors, GStyleSheet } from '@/utils/DarkMode';
import RecordItem from './components/RecordItem';
import Taro from '@tarojs/taro';
import userState from '@/models/userState';
import { payHandler } from './unit';

interface RechargeRecord {
  id: string;
  amount: number;
  create_time: number;
  device_id: string;
  good: {
    id: string;
    name: string;
    desc: string;
    icon_url: string;
    price: number;
  };
  pay_time: number;
  status: number;
  update_time: number;
}

interface RechargeResponse {
  success: boolean;
  data: {
    data: RechargeRecord[];
  };
}

const dstyle = GStyleSheet.create({
  list: {
  },
  listInner: {
    paddingLeft: 20,
    paddingRight: 20,
  },
  emptyContainer: {
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
    marginTop: 100,
  },
  emptyText: {
    fontSize: 14,
    color: DynamicColors.normalTextGaryColor,
    marginTop: 12,
  },
});

export default () => {
  const styles = dstyle.useDynamicStyle();
  const [recordList, setRecordList] = useState<RechargeRecord[]>([]);

  useEffect(() => {
    loadData();

    const timer = setInterval(() => {
      loadData();
    }, 1000 * 3);

    return () => {
      clearInterval(timer);
    }
  }, []);

  const loadData = () => {
    getRechargeRecordList().then((res: RechargeResponse) => {
      if (res.success) {
        setRecordList(res.data.data);
      }
    });
  }

  const handlePayClick = async (record: RechargeRecord) => {
    Taro.showLoading({
      title: '加载中...',
    });
    try {
        const payData = record.pay_info;
        await payHandler(record.id, payData)
        loadData();
    } catch (error) {
      console.error('支付失败:', error);
      Taro.showToast({
        title: '支付失败',
        icon: 'none'
      });
    } finally {
      Taro.hideLoading();
    }
  };

  if (recordList.length === 0) {
    return (
      <PageContainer title="充值记录">
        <View style={styles.emptyContainer}>
          <Text style={styles.emptyText}>暂无充值记录</Text>
        </View>
      </PageContainer>
    );
  }

  return (
    <PageContainer title="充值记录">
      <FlexScrollView id='deleteScrollList' scrollStyle={styles.list}>
        <View style={styles.listInner}>
          {recordList.map((record) => (
            <RecordItem 
              key={record.id} 
              record={record}
              onPayClick={handlePayClick}
            />
          ))}
        </View>
        
      </FlexScrollView>
    </PageContainer>
  );
};